//
//  HTTPTool.m
//  NSURLSession封装
//
//  Created by 周成龙 on 16/11/1.
//  Copyright © 2016年 ZCL. All rights reserved.
//

#import "HTTPTool.h"
#import "NSString+JSON.h"


@interface HTTPTool ()<NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate>

@property (nonatomic, strong) NSMutableData *dataM;

@end

@implementation HTTPTool

static HTTPTool *_instance;

+ (instancetype)shareHTTPTool {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[HTTPTool  alloc] init];
    });
    return _instance;
}

- (id)init {
    if (self = [super init]) {
        
        NSURL *url = [NSURL URLWithString:@"http://siyi.api.xt-cloud.com/show"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        // 默认就是GET请求，要发POST请求的话，就必须更改请求方式
        request.HTTPMethod = @"POST";
        
        NSDictionary *dict = @{@"action":@"getShowIndex"};
        NSString *bodyString = [NSString JSONStringWithDiction:dict];
        request.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
        [task resume];
    }
    return self;
}

- (void)postCopleteData:(completeBlock)completeBlock {
    _completeBlock = completeBlock;
}

#pragma mark - NSURLSessionDelegate

#pragma mark - NSURLSessionTaskDelegate
// 请求完成 / 失败 的时候调用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error {
    //解析服务器返回数据
//    NSLog(@"-1-%@", [[NSString alloc] initWithData:self.dataM encoding:NSUTF8StringEncoding]);
    
    if (_completeBlock) {
        _completeBlock(self.dataM, error ? error:nil);
    }
}

#pragma mark - NSURLSessionDataDelegate
// 接收 到服务器 响应 的时候调用
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    
    //子线程中执行
    NSLog(@"当前线程 --> %@", [NSThread currentThread]);
    
    self.dataM = [NSMutableData data];
    //默认情况下不接收数据
    //必须告诉系统是否接收服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);
}

// 接受 到服务器 返回 数据的时候调用,可能被调用多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data {
    //拼接 服务器返回的 数据
    [self.dataM appendData:data];
}

@end
